package com.sike.netty.im.client.handler;

import com.sike.netty.im.client.event.ListGroupMembersEvent;
import com.sike.netty.im.client.service.BeanFactory;
import com.sike.netty.im.client.service.ClientService;
import com.sike.netty.im.common.command.CommandBody;
import com.sike.netty.im.common.command.ListGroupMembersRequestCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Scanner;

/**
 * 查询群聊成员 handler
 *
 * @author chenssy
 * @date 2023/09/21
 */
public class ListGroupMembersRequestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof ListGroupMembersEvent) {
            ClientService clientService = (ClientService) BeanFactory.getServiceBean(ClientService.class);
            // 获取群聊成员列表界面
            listGroupMembersMenu();

            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                String[] lines;
                while (true) {
                    lines = scanner.nextLine().split(" ");
                    switch (lines[0]) {
                        case "01":
                            doListGroupMembers(ctx,lines);
                            break;
                        case "02":
                            clientService.toMainMenu(ctx);
                            return;
                        case "00":
                            clientService.exitLogin(ctx);
                            return;
                    }
                }
            }).start();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 获取群聊成员列表
     * @param ctx
     * @param lines
     */
    private void doListGroupMembers(ChannelHandlerContext ctx, String[] lines) {
        ListGroupMembersRequestCommand requestCommand = new ListGroupMembersRequestCommand(lines[1]);
        Message message = MessageBuilder.buildMessage(requestCommand,null,null);
        ctx.channel().writeAndFlush(message);
    }

    private void listGroupMembersMenu() {
        System.out.println("|-------------------------------------|");
        System.out.println("|            获取群成员界面             |");
        System.out.println("|获取群成员：01 groupId                   |");
        System.out.println("|02:返回主菜单                          |");
        System.out.println("|00:退出登录                            |");
        System.out.println("|------------------------------------- |");
    }
}
